package com.andnux.android.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.andnux.android.MainApp;
import com.andnux.android.adapter.OnItemClickListener;
import com.andnux.android.adapter.PhotoAdapter;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.data.Works;
import com.andnux.android.databinding.ActivityPublishBinding;
import com.andnux.android.databinding.ItemImageBinding;
import com.andnux.android.dialog.DialogFactory;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.GsonUtils;
import com.andnux.android.network.NotNullConsumer;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.andnux.android.network.SuccessConsumer;
import com.andnux.android.utils.GlideEngine;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class PublishActivity extends BaseActivity<ActivityPublishBinding> {

    private static final String TAG = "PublishActivity";
    private final List<String> photos = new ArrayList<>();
    private PhotoAdapter adapter;
    private static final int REQUEST_CODE = 0x99;
    private final Works works = new Works();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new PhotoAdapter();
        photos.add("-");
        adapter.setOnItemClickListener(new OnItemClickListener<ItemImageBinding>() {
            @Override
            public void onItemClick(ItemImageBinding view, int position, long id) {
                if (position == photos.size() - 1) {
                    PictureSelector.create(PublishActivity.this)
                            .openGallery(SelectMimeType.ofAll())
                            .setMaxSelectNum(6)
                            .setImageEngine(GlideEngine.createGlideEngine())
                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    uploadFiles(result);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });

                } else {

                }
            }
        });
        binding.content.setAdapter(adapter);
        adapter.setNewData(photos);

        SystemUsers users = MainApp.getApp().getSystemUsers();
        if ("2".equalsIgnoreCase(users.getRole())) {
            binding.title.setText("发布作品");
        } else {
            binding.title.setText("发布需求");
        }
        binding.priceLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showInputDialog(PublishActivity.this,
                        "价格", "0.00", "请输入价格",
                        new DialogFactory.OnEditInputClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, String content) {
                        try {
                            double aDouble = Double.parseDouble(content);
                            works.setPrice(aDouble);
                            binding.price.setText(content);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(PublishActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String titleText = binding.titleText.getText().toString();
                String text = binding.text.getText().toString();
                if (TextUtils.isEmpty(titleText) || TextUtils.isEmpty(text) || photos.size() <= 1) {
                    Toast.makeText(PublishActivity.this, "请添加描述和图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                DesignCloudApi api = RetrofitClient.getInstance().getServerApi();
                works.setContent(text);
                SystemUsers users = MainApp.getApp().getSystemUsers();
                if ("2".equalsIgnoreCase(users.getRole())) {
                    works.setLx("0");
                } else {
                    works.setLx("1");
                }
                works.setTitle(titleText);
                works.setCreateTime(new Date());
                works.setCreator(String.valueOf(users.getId()));

                works.setViews(0);
                works.setStar(0);
                works.setDeleted(0);
                works.setUserId(String.valueOf(users.getId()));
                List<String> list = new ArrayList<>();
                for (String photo : photos) {
                    if (!photo.equalsIgnoreCase("-")) {
                        list.add(photo);
                    }
                }
                works.setFiles(GsonUtils.gson.toJson(list));
                addDisposable(api.worksSave(works)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SuccessConsumer<Result<Works>>() {
                            @Override
                            public void onSuccess(Result<Works> result) {
                                Toast.makeText(PublishActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                if (throwable != null) {
                                    Toast.makeText(PublishActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }));
            }
        });
    }

    @Override
    protected void onDestroy() {
        adapter.stop();
        super.onDestroy();
    }

    private void uploadFiles(ArrayList<LocalMedia> result) {
        DesignCloudApi api = RetrofitClient.getInstance().getServerApi();
        for (LocalMedia s : result) {
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
            File file = new File(s.getRealPath());
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("file", file.getName(), imageBody);
            addDisposable(api.fileUpload(builder.build().parts())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new NotNullConsumer<Result<String>>() {
                        @Override
                        public void onSuccess(Result<String> result) {
                            photos.add(0, result.getData());
                            adapter.setNewData(photos);
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            if (throwable != null) {
                                Toast.makeText(PublishActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }));
        }
    }
}